package cn.stylefeng.guns.core.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;

public class FileUtil {



    public static String saveImage(MultipartFile multipartFile,String webappRoot,  HttpServletRequest request){
        InputStream is = null;
        OutputStream os = null;
        String fileName = null;
        String path = null;
        try {
            is = multipartFile.getInputStream();
            String name = multipartFile.getOriginalFilename();
            int index = name.lastIndexOf(".");//获取文件名中的点的位置
            String substring = name.substring(index - 1, name.length());
            fileName = UUIDutil.randomUUId()+(new Date()).getTime() + substring;   //文件名随机
            path = webappRoot + "src/main/webapp/assets/common/images/carimg/"; //获取web上下文路径
            byte[] bs = new byte[1024];   //设置缓冲区
            File file = new File(path);
            if (!file.exists()) {   //如果有则退出  如果没有则创建
                file.mkdirs();
            }
            int len;    //数据长度
            os = new FileOutputStream(path + fileName);   //写入文件的目录
            while ((len = is.read(bs)) != -1) {    //循环写入
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "/assets/common/images/carimg/" + fileName;
    }
}
